from PyQt4 import uic
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.phonon import Phonon
import qtvlc

import gorilla
import sys

app = QtGui.QApplication(sys.argv)
window = uic.loadUi('crawler.ui')
global vlcp
vlcp=qtvlc.Player(window)
vlcp.setGeometry(QtCore.QRect(0, 10, 601, 351))
window.show()

model=QtGui.QStandardItemModel()
proxyModel=QtGui.QSortFilterProxyModel()
proxyModel.setSourceModel(model)
proxyModel.setFilterCaseSensitivity(False)
window.series.setModel(proxyModel)
#window.series.setRootIndex(proxyModel.mapFromSource(model.index(model.rootPath())))

global ws

ws=gorilla.watchserieseu()
series_names=ws.get_serie_names()
for name in sorted(series_names):
	model.appendRow(QtGui.QStandardItem(name))

def update_rcl(qindex):
	global ws
	window.episodes.clear()
	item=model.itemFromIndex(qindex.model().mapToSource(qindex))
	serie=str(item.text())
	serie=ws.get_serie(serie)
	update_seasons(serie)

def update_seasons(serie):
	seasons=serie.get_seasons()
	for season in seasons:
		skey=QtGui.QTreeWidgetItem(["Season "+str(season.number)])
		episodes=season.get_episodes()
		for episode in episodes:
			ekey=QtGui.QTreeWidgetItem([episode.name])
			skey.addChild(ekey)
			setattr(ekey,"epi",episode)
			setattr(ekey,"videos",[])
		window.episodes.addTopLevelItem(skey)

def update_epis(qtreeitem):
	if hasattr(qtreeitem,"epi"):
		links=qtreeitem.epi.get_videos()
		videos=qtreeitem.videos
		i=0
		for link in links:
			if not link in videos:
				mkey=QtGui.QTreeWidgetItem(["Mirror "+ str(i)])
				qtreeitem.addChild(mkey)
				setattr(mkey,"link",link)
				qtreeitem.videos.append(link)
				qtreeitem.setExpanded(True)
				i+=1
	if hasattr(qtreeitem,"link"):
		global vlcp
		vlcp.OpenStream(qtreeitem.link)
		print qtreeitem.link

QtCore.QObject.connect(window.sfilter, QtCore.SIGNAL("textChanged(QString)"),proxyModel, QtCore.SLOT("setFilterFixedString(QString)"))
QtCore.QObject.connect(window.series, QtCore.SIGNAL("clicked(QModelIndex)"),update_rcl)
QtCore.QObject.connect(window.episodes, QtCore.SIGNAL("itemClicked(QTreeWidgetItem*, int)"),update_epis)

sys.exit(app.exec_())